﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Net;
using System.Web.Security;
using System.Web.Profile;

using EHTSaleManager.Code.BLL;
using EHTSaleManager.Code.Utility;

namespace EHTSaleManager
{
    public partial class IndexCustomerProfile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                DataSet dsRegion = RegionProvider.GetRegions();
                this.ddlRegion.DataValueField = "RegionID";
                this.ddlRegion.DataTextField = "RegionName";
                this.ddlRegion.DataSource = dsRegion;
                this.ddlRegion.DataBind();

                DataSet dsLevelService = ServiceLevelsProvider.GetServiceLevels();
                this.ddlServiceLevel.DataValueField = "SeviceLevelID";
                this.ddlServiceLevel.DataTextField = "Description";
                this.ddlServiceLevel.DataSource = dsLevelService;
                this.ddlServiceLevel.DataBind();

                // get customer
                MembershipUser theUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
                ProfileBase theProfile = ProfileBase.Create(HttpContext.Current.User.Identity.Name);

                this.txtAddress.Text = theProfile.GetPropertyValue("Address").ToString();
                this.txtCity.Text = theProfile.GetPropertyValue("City").ToString();
                this.txtEmail.Text = theProfile.GetPropertyValue("Email").ToString();
                this.txtFax.Text = theProfile.GetPropertyValue("Fax").ToString();
                this.txtFirstName.Text = theProfile.GetPropertyValue("FirstName").ToString();
                this.txtLastName.Text = theProfile.GetPropertyValue("LastName").ToString();
                this.txtPhone.Text = theProfile.GetPropertyValue("Phone").ToString();
                this.txtPostCode.Text = theProfile.GetPropertyValue("PostCode").ToString();
                this.ddlRegion.SelectedValue = theProfile.GetPropertyValue("RegionID").ToString();
                String serviceLevel = theProfile.GetPropertyValue("ServiceLevelID").ToString();

                if (serviceLevel != String.Empty)
                    this.ddlServiceLevel.SelectedValue = serviceLevel;
                else
                    this.ddlServiceLevel.SelectedValue = "-1";

                string SignatureUrl = theProfile.GetPropertyValue("SignatureUrl").ToString();

                if (string.IsNullOrEmpty(SignatureUrl) == false)
                {
                    if ((RemoteFileExists(@"~\ImageDatas\Signatures\" + SignatureUrl)) == false)
                    {
                        this.picSignature.ImageUrl = @"~\ImageDatas\Signatures\" + SignatureUrl;
                    }
                    else
                    {
                        this.picSignature.ImageUrl = @"~\ImageDatas\Signatures\noImage.gif";
                    }


                }
                else
                {
                    this.picSignature.ImageUrl = @"~\ImageDatas\Signatures\noImage.gif";
                }
                //this.lblTotalAccount.Text = theProfile.GetPropertyValue("ToltalAccount").ToString();
                //// Load Apending Order
                //DataSet ListOrderApending = OrderProvider.GetOrdersForOrderState(theUser.ProviderUserKey.ToString(), 1);
                //rqApendingOrder.DataSource = ListOrderApending;
                //rqApendingOrder.DataBind();

            }

        }
        private bool RemoteFileExists(string url)
        {
            bool result = false;
            using (System.Net.WebClient client = new WebClient())
            {
                try
                {
                    Stream stream = client.OpenRead(url);
                    if (stream != null)
                    {
                        result = true;
                    }
                    else
                    {
                        result = false;
                    }
                }
                catch
                {
                    //Any exception will returns false.
                    result = false;
                }
            }
            return result;
        }
        private Boolean ValidateData()
        {
            String message = "";
            Boolean isSuccess = true;

            if (ddlRegion.SelectedValue == "-1")
            {
                message += "Chose Region <br />";
                isSuccess = false;
            }

            if (ddlServiceLevel.SelectedValue == "-1")
            {
                message += "Chose Service Level <br />";
                isSuccess = false;
            }

            string sExtendsion = ".gif|.GIF|.jpg|.JPG|.png|.PNG";

            try
            {
                if (this.funSignature.HasFile && sExtendsion.IndexOf(Path.GetExtension(funSignature.PostedFile.FileName)) < 0)
                {
                    isSuccess = false;
                    message = "Upload picture only.";
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
            }

            if (!isSuccess)
                ltrMessage.Text = message;

            return isSuccess;
        }

        protected void ddlRegion_DataBound(object sender, EventArgs e)
        {
            this.ddlRegion.Items.Insert(0, new ListItem("select region ...", "-1"));
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidateData())
                return;

            Page.Validate();

            if (Page.IsValid)
            {
                ProfileBase theProfile = ProfileBase.Create(HttpContext.Current.User.Identity.Name);
                theProfile.SetPropertyValue("FirstName", this.txtFirstName.Text.Trim());
                theProfile.SetPropertyValue("LastName", this.txtLastName.Text.Trim());
                theProfile.SetPropertyValue("Email", this.txtEmail.Text.Trim());
                theProfile.SetPropertyValue("Phone", this.txtPhone.Text.Trim());
                theProfile.SetPropertyValue("Fax", this.txtFax.Text.Trim());
                theProfile.SetPropertyValue("City", this.txtCity.Text.Trim());
                theProfile.SetPropertyValue("Address", this.txtAddress.Text.Trim());
                theProfile.SetPropertyValue("RegionID", Int32.Parse(this.ddlRegion.SelectedValue));
                theProfile.SetPropertyValue("PostCode", this.txtPostCode.Text.Trim());
                theProfile.SetPropertyValue("ServiceLevelID", Int32.Parse(this.ddlServiceLevel.SelectedValue));
                if (this.funSignature.HasFile)
                {
                    String fileName = funSignature.PostedFile.FileName;
                    String fileType = Path.GetExtension(fileName);
                    String newFileName = DateTime.Now.Ticks.ToString() + fileType;
                    string str = Server.MapPath("~/");
                    str += "ImageDatas\\Signatures\\";
                    DirectoryInfo directory = new DirectoryInfo(str);

                    if (!directory.Exists)
                    {
                        DirectoryInfo drt = new DirectoryInfo("\\ImageDatas");
                        if (!drt.Exists)
                        {
                            directory = new DirectoryInfo(Server.MapPath("~/"));

                            directory = directory.CreateSubdirectory("ImageDatas");

                        }
                        directory = new DirectoryInfo(Server.MapPath("~/").ToString() + "\\ImageDatas");
                        directory = directory.CreateSubdirectory("Signatures");
                    }
                    funSignature.PostedFile.SaveAs(Server.MapPath("~/") + "ImageDatas//Signatures//" + newFileName);
                    theProfile.SetPropertyValue("SignatureUrl", newFileName);
                    this.picSignature.ImageUrl = @"~\ImageDatas\Signatures\" + newFileName;
                }
                else
                {
                    if (string.IsNullOrEmpty(theProfile.GetPropertyValue("SignatureUrl").ToString()))
                    {
                        theProfile.SetPropertyValue("SignatureUrl", "");
                    }
                    else
                    {
                        theProfile.SetPropertyValue("SignatureUrl", theProfile.GetPropertyValue("SignatureUrl").ToString());
                    }

                }
                theProfile.Save();
            }
        }

        protected void ddlServiceLevel_DataBound(object sender, EventArgs e)
        {
            this.ddlServiceLevel.Items.Insert(0, new ListItem("--Level Service--", "-1"));
        }

    }
}